package com.linzm.leetcode.primary.字符串;

import org.junit.Test;

/**
 * @Author zimingl
 * @Date 2022/10/7 0:39
 * @Description: TODO
 */
public class 字符串541反转字符串II {
    public String reverseStr(String s, int k) {
        char[] ch = s.toCharArray();
        for(int i = 0; i < ch.length; i += 2 * k){
            int start = i;
            //这里是判断尾数够不够k个来取决end指针的位置
            int end = Math.min((ch.length - 1), (start + k - 1));
            //用异或运算反转
            while(start < end){
                swap(ch, start ++, end --);
            }
        }
        return new String(ch);
    }

    public void swap(char[] nums, int a, int b){
        char temp = nums[a];
        nums[a] = nums[b];
        nums[b] = temp;
    }

    @Test
    public void test(){
        String s = "abcdefg";
        int k = 2;
        System.out.println( reverseStr2(s, k) );
    }

    private static void swap2(char[] nums, int a, int b){
        char temp = nums[a];
        nums[a] = nums[b];
        nums[b] = temp;
    }

    private static String reverseStr2(String s, int k){
        char[] chars = s.toCharArray();
        for (int i = 0; i < chars.length; i += 2*k) {
            int start = i;
            int end = Math.min(chars.length - 1, start + k - 1);
            while (start <= end){
                swap2(chars, start ++, end --);
            }
        }
        return new String(chars);
    }
}
